package com.bw.message.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.easysdk.factory.Factory;
import com.bw.common.redis.service.RedisService;
import com.bw.message.config.AliPayConfig;
import com.bw.message.domain.PaymentFlow;
import com.bw.message.domain.vo.AliPay;
import com.bw.message.service.PaymentFlowService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.HashMap;
import java.util.Map;

/**
 * 支付宝支付
 */
@Component
@RestController
@RequestMapping("alipay")
@Transactional(rollbackFor = Exception.class)
public class PaymentController implements HandlerInterceptor {
    @Autowired
    private PaymentFlowService paymentFlowService;
    @Autowired
    private RedisService redisService;
    @Resource
    AliPayConfig aliPayConfig;


    private static final String GATEWAY_URL ="https://openapi-sandbox.dl.alipaydev.com/gateway.do";
    private static final String FORMAT ="JSON";
    private static final String CHARSET ="utf-8";
    private static final String SIGN_TYPE ="RSA2";

    @GetMapping("/pay") // 前端路径参数格式?subject=xxx&traceNo=xxx&totalAmount=xxx
    public void pay(AliPay aliPay, HttpServletResponse httpResponse) throws Exception {
        AlipayClient alipayClient = new DefaultAlipayClient(GATEWAY_URL, aliPayConfig.getAppId(),
                aliPayConfig.getAppPrivateKey(), FORMAT, CHARSET, aliPayConfig.getAlipayPublicKey(), SIGN_TYPE);
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
        request.setNotifyUrl(aliPayConfig.getNotifyUrl());
        request.setReturnUrl(aliPayConfig.getReturnUrl());
        request.setBizContent("{\"out_trade_no\":\"" + aliPay.getTraceNo() + "\","
                + "\"total_amount\":\"" + aliPay.getTotalAmount() + "\","
                + "\"subject\":\"" + aliPay.getSubject() + "\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
        String form = "";
        try {
            // 调用SDK生成表单
            form = alipayClient.pageExecute(request).getBody();
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        httpResponse.setContentType("text/html;charset=" + CHARSET);
        // 直接将完整的表单html输出到页面
        httpResponse.getWriter().write(form);
        httpResponse.getWriter().flush();
        httpResponse.getWriter().close();
    }

    @PostMapping("/notify")  // 注意这里必须是POST接口
    public String payNotify(HttpServletRequest request) throws Exception {
        if (request.getParameter("trade_status").equals("TRADE_SUCCESS")) {
            System.out.println("=========支付宝异步回调========");

            Map<String, String> params = new HashMap<>();
            Map<String, String[]> requestParams = request.getParameterMap();
            for (String name : requestParams.keySet()) {
                params.put(name, request.getParameter(name));
            }

            //订单号
            String tradeNo = params.get("out_trade_no");
            // 支付时间
            String gmtPayment = params.get("gmt_payment");
            // 支付宝交易凭证号
            String alipayTradeNo = params.get("trade_no");

            // 验证支付宝通知的签名是否有效
            if (Factory.Payment.Common().verifyNotify(params)) {
                // 验签通过，处理支付成功逻辑
                System.out.println("交易名称: " + params.get("subject"));
                System.out.println("交易状态: " + params.get("trade_status"));
                System.out.println("支付宝交易凭证号: " + params.get("trade_no"));
                System.out.println("商户订单号: " + params.get("out_trade_no"));
                System.out.println("交易金额: " + params.get("total_amount"));
                System.out.println("买家在支付宝唯一id: " + params.get("buyer_id"));
                System.out.println("买家付款时间: " + params.get("gmt_payment"));
                System.out.println("买家付款金额: " + params.get("buyer_pay_amount"));

                // 在此处进行更新订单为已支付的操作
                // 验签通过，处理支付成功逻辑
                PaymentFlow paymentFlow = new PaymentFlow();
                paymentFlow.setOutTradeNo(params.get("out_trade_no"));
                paymentFlow.setTradeNo(params.get("trade_no"));
                paymentFlow.setTotalAmount(params.get("total_amount"));
                paymentFlow.setSubject(params.get("subject"));
                paymentFlow.setTradeStatus(params.get("trade_status"));
                paymentFlow.setGmtPayment(params.get("gmt_payment"));
                paymentFlow.setBuyerId(params.get("buyer_id"));
                paymentFlow.setBuyerPayAmount(params.get("buyer_pay_amount"));

                if(redisService.hasKey("doctorName")){
                    redisService.deleteObject("doctorName");
                    redisService.setCacheObject("doctorName",params.get("subject"));
                }else {
                    redisService.setCacheObject("doctorName",params.get("subject"));
                }

//                 保存支付流水记录到数据库（这里假设有一个service来处理数据库操作）
               paymentFlowService.add(paymentFlow);

            }
        }
        return "success";
    }
}




